from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.urls import reverse
# 免除csrf验证
from django.views.decorators.csrf import csrf_exempt
from web.form.wiki import WikiModelForm
from web import models
from utils.encrypt import uid
from utils.tencent.cos import uploadfile


def wiki(request, project_id):
    wiki_id = request.GET.get('wiki_id')
    # 判断是否位数字，有可能是字符串
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'web/wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'web/wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'web/wiki_add.html', {'form': form})
    form = WikiModelForm(request, request.POST)
    if form.is_valid():
        # 判断用户是否选择父目录
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project
        form.save()
        url = reverse('web_wiki', kwargs={'project_id': project_id})
        return redirect(url)


def wiki_catalog(request, project_id):
    """获取wiki目录"""  # values（）产生的是字典  values_list是元组  他们都在列表里
    data = models.Wiki.objects.filter(project_id=project_id).values("id", 'title', 'parent_id').order_by('depth', 'id')
    # print(data)
    # print(list(data))
    return JsonResponse({'status': True, 'data': list(data)})


def wiki_delete(request, project_id, wiki_id):
    """删除文章"""
    models.Wiki.objects.filter(id=wiki_id, project_id=project_id).delete()
    url = reverse('web_wiki', kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    """编辑文章"""
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    if not wiki_object:
        url = reverse('web_wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'web/wiki_add.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('web_wiki', kwargs={'project_id': project_id})
        preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(preview_url)
    return render(request, 'web/wiki_add.html', {'form': form})


# 免除csrf验证
@csrf_exempt
def wiki_upload(request, project_id):
    """markdown插件上传图片"""
    result = {
        'success': 0,
        'message': None,
        'url': None
    }

    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = "文件不存在"
        return JsonResponse(result)
    # 文件后缀名
    ext = image_object.name.rsplit('.')[-1]
    key = "{}.{}".format(uid(request.tracer.user.phone), ext)
    bucket = request.tracer.project.bucket
    region = 'ap-chengdu'
    # 文件对象上传到当前项目的桶中
    image_url = uploadfile(bucket, region, image_object, key)
    # print(image_url)
    result['success'] = 1
    result['url'] = image_url

    print(result)
    return JsonResponse(result)
